<template>
  <div class="department-container">
    <div class="app-container">
      <PageTools :title="'总记录条数:' + total + '条'">
        <el-button
          type="warning"
          size="small"
          @click="$router.push('/import')"
        >excel导入</el-button>
        <el-button
          type="danger"
          size="small"
          @click="hEportExcel"
        >excel导出</el-button>
        <el-button
          type="primary"
          size="small"
          @click="hAdd"
        >新增员工</el-button>
      </PageTools>

      <el-card style="margin-top: 10px">
        <el-table border :data="list">
          <el-table-column label="序号" type="index" :index="indexMethod" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template v-slot="scope">
              {{ format(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" />
          <el-table-column label="账户状态">
            <el-switch
              v-model="value"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
          </el-table-column>
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id=' + scope.row.id)">查看</el-button>
              <el-button type="text" size="small">分配角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="hDel(scope.row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <!-- 分页组件 -->
          <el-pagination
            :current-page="page"
            :page-sizes="[1, 2, 3, 5]"
            :page-size="size"
            :total="total"
            layout="total,sizes,prev,pager,next"
            @size-change="hSizeChange"
            @current-change="hCurrentChange"
          />
        </el-row>
      </el-card>
    </div>
    <el-dialog
      title="新增员工"
      :visible.sync="showDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="hClose"
    >
      <emp-dialog ref="refDialog" @success="hSuccess" @close="hCancel" />
    </el-dialog>
  </div>
</template>

<script>
import { delEmployee, getEmployeeList } from '@/api/employee'
import { TYPE_MAP } from '@/comstant/index'
import EmpDialog from './EmpDialog.vue'
export default {
  components: { EmpDialog },
  data() {
    return {
      showDialog: false, // 对话框的显示隐藏
      value: true,
      list: [],
      total: 0, // 总条数
      page: 1, // 页码
      size: 2 // 每页显示多少条
    }
  },
  created() {
    this.loadEmplyees()
  },
  methods: {
    formData(rows) {
      // 英文的key
      const enKeys = Object.keys(rows[0])
      console.log(enKeys)
      const mapObj = {
        id: '编号',
        password: '密码',
        mobile: '手机号',
        username: '姓名',
        timeOfEntry: '入职日期',
        formOfEmployment: '聘用形式',
        correctionTime: '转正日期',
        workNumber: '工号',
        departmentName: '部门',
        staffPhoto: '头像地址'
      }
      // 中文的key
      const header = enKeys.map((key) => mapObj[key])
      console.log(header)
      const data = rows.map((item) => {
        item.formOfEmployment = TYPE_MAP[item.formOfEmployment]
        return Object.values(item)
      })
      console.log(data)
      return { header, data }
    },
    async hEportExcel() {
      const res = await getEmployeeList({ page: this.page, size: this.size })
      const { header, data } = this.formData(res.data.rows)
      import('@/vendor/Export2Excel').then((excel) => {
        // excel表示导入的模块对象
        console.log(excel)
        excel.export_json_to_excel({
          header, // 表头 必填
          data, // 具体数据 必填
          filename: '员工信息', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    hClose() {
      this.$refs.refDialog.resetForm()
    },
    hCancel() {
      // 关闭弹框
      this.showDialog = false
    },
    hSuccess() {
      // 关闭弹框
      this.showDialog = false
      this.total++
      this.page = Math.ceil(this.total / this.size)
      // 重新加载数据
      this.loadEmplyees()
    },
    hAdd() {
      // 打开弹框
      this.showDialog = true
    },
    async doDel(id) {
      try {
        // 1.发送请求
        await delEmployee(id)
        // 2.提示
        this.$message.success('删除成功')
        // 3.重发请求
        this.loadEmplyees()
      } catch (err) {
        console.log(err)
        this.$message.error('删除失败')
      }
    },
    // 用户点击删除
    hDel(id) {
      this.$confirm('您确定要删除吗, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          //  确认
          if (this.list.length === 1 && this.page > 1) {
            this.page--
          }
          this.doDel(id)
        })
        .catch(() => {
          // 取消
        })
    },
    // 序号
    indexMethod(index) {
      return index + (this.page - 1) * this.size + 1
    },
    // 更新页码
    hCurrentChange(val) {
      this.page = val
      // 重新加载数据
      this.loadEmplyees()
    },
    // 更新每页显示多少条
    hSizeChange(val) {
      this.pagesize = val
      // 每次更新页数,页码为1
      this.page = 1
      // 重新加载数据
      this.loadEmplyees()
    },
    // 设置聘用形式
    format(id) {
      return TYPE_MAP[id] || '未知'
    },
    async loadEmplyees() {
      const res = await getEmployeeList({
        page: this.page,
        size: this.size
      })
      this.list = res.data.rows
      this.total = res.data.total
    }
  }
}
</script>
